package com.yinhe.music.yhmusic.adapter;

import android.os.Parcelable;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.view.ViewGroup;

import com.yinhe.music.yhmusic.search.ISearchFragment;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 分类标签
 *
 * @author hasee
 * @date 2017/8/14
 */

public class TabAdapter extends FragmentStatePagerAdapter {
    private List<Fragment> mFragments;
    private String[] mFragmentTitles;
    private Map<Integer, Fragment> mFragmentMap = new HashMap<>();

    /**
     * 更新标签文字
     *
     * @param mFragmentTitles 标签集合
     */
    public void update(String[] mFragmentTitles) {
        this.mFragmentTitles = mFragmentTitles;
        notifyDataSetChanged();
    }

    public TabAdapter(FragmentManager fm, List<Fragment> mFragments, String[] mFragmentTitles) {
        super(fm);
        this.mFragments = mFragments;
        this.mFragmentTitles = mFragmentTitles;
    }

    public void updateFragmentForKey(String key) {
        if (mFragments != null) {
            for (Fragment fragment : mFragments) {
                if (fragment instanceof ISearchFragment) {
                    ((ISearchFragment) fragment).updateDataForKey(key);
                }
            }
        }
    }


    @NonNull
    @Override
    public Object instantiateItem(@NonNull ViewGroup container, int position) {
        Fragment fragment = (Fragment) super.instantiateItem(container, position);
        //记录每个position位置最后显示的Fragment
        mFragmentMap.put(position, fragment);
        return fragment;
    }

    @Override
    public Fragment getItem(int position) {
        return mFragments.get(position);
    }

    @Override
    public int getCount() {
        if (mFragmentTitles == null) {
            return 0;
        }
        return mFragmentTitles.length;
    }


    @Override
    public CharSequence getPageTitle(int position) {
        return mFragmentTitles[position];
    }

    @Override
    public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {

    }

    @Override
    public Parcelable saveState() {
        return null;
    }
}
